#!/usr/bin/env sh
export BUILDX_NO_DEFAULT_LOAD=true

: ${PREFER_BUILDCTL=}
: ${PREFER_LEGACY=}
: ${CI=}
: ${GITHUB_ACTIONS=}
: ${CACHEDIR_FROM=}
: ${CACHEDIR_TO=}

if [ "$PREFER_BUILDCTL" = "1" ]; then
  echo >&2 "WARNING: PREFER_BUILDCTL is no longer supported. Ignoring."
fi

if [ "$PREFER_LEGACY" = "1" ]; then
  echo >&2 "WARNING: PREFER_LEGACY is no longer supported. Ignoring."
fi

progressFlag=""
if [ "$CI" = "true" ]; then
  progressFlag="--progress=plain"
fi

buildxCmd() {
  if docker buildx version >/dev/null 2>&1; then
    set -x
    docker buildx "$@" $progressFlag
  elif buildx version >/dev/null 2>&1; then
    set -x
    buildx "$@" $progressFlag
  else
    topdir="$(realpath $(dirname "$0")/..)"
    if [ ! -x "${topdir}/bin/buildx" ]; then
      set -x
      "${topdir}/hack/install-buildx"
    fi
    set -x
    bootstrapName="moby-buildkit"
    "${topdir}/hack/bootstrap-buildx" "${bootstrapName}"
    BUILDX_BUILDER="${bootstrapName}" "${topdir}/bin/buildx" "$@" $progressFlag
  fi
}

cacheType=""
cacheRefFrom=""
cacheRefTo=""
currentref=""
if [ "$GITHUB_ACTIONS" = "true" ]; then
  currentref="git://github.com/$GITHUB_REPOSITORY#$GITHUB_REF"
  cacheType="local"
  cacheRefFrom="$CACHEDIR_FROM"
  cacheRefTo="$CACHEDIR_TO"
fi

currentcontext="."
if [ -n "$currentref" ]; then
  currentcontext="--build-arg BUILDKIT_CONTEXT_KEEP_GIT_DIR=1 $currentref"
fi
